<template>
    <div>
        <div class="ccui-navigation">
            <!-- 面包屑 -->
            <el-button
                size="mini"
                type="primary-icon-medium"
                icon="icon-ccui-return"
                @click="handleBack"
            >返回
            </el-button>
            <div class="ccui-navigation-divider"/>
            <!-- 面包屑 -->
            <el-breadcrumb
                class="ccui-navigation-crumbs-container"
                separator-class="el-icon-arrow-right"
            >
                <el-breadcrumb-item
                    :to="{ path: $store.getters.getBreadcrumb('level1').path }"
                >{{ $store.getters.getBreadcrumb("level1").name }}
                </el-breadcrumb-item>
                <el-breadcrumb-item
                    :to="{
            path: '/settlement-management/settlement-maintenance-approval'
          }"
                >结算管理
                </el-breadcrumb-item>
                <el-breadcrumb-item
                    :to="{
            path: '/settlement-management/settlement-maintenance-approval'
          }"
                >物资结算管理
                </el-breadcrumb-item>
                <el-breadcrumb-item
                    :to="{
            path: breadUrl
          }"
                >结算单维护
                </el-breadcrumb-item>
                <el-breadcrumb-item>
          <span class="ccui-curr-crumb"
          >编辑 {{ settlementForm.settlementName }}</span
          >
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div v-if="isTrue" class="ccui-app-container-detail">
            <div class="ccui-app-container-detail-body">
                <el-tabs v-model="activeName" class="el-tabs__customize" @tab-click="clickTabs">
                    <el-tab-pane label="基本信息" name="first">
                        <baseInfo
                            ref="baseInfo"
                            :detail="detailInfo"
                            :myId="myId"
                            :settlementForm="settlementForm"
                            :settlementList="settlementList"
                            :file-list="fileList"
                            showSummary
                        />
                    </el-tab-pane>
                    
                    <el-tab-pane label="结算单明细" name="second">
                        <keep-alive>
                            <financeInfo
                                ref="financeInfo"
                                :detail="detailInfo"
                                :settlementList.sync="settlementList"
                                :settlementForm="settlementForm"
                                @numrows="numrows"
                                @delrows="delrows"
                                v-if="showFinanceInfo"
                            />
                        </keep-alive>
                    </el-tab-pane>
                    
                    <el-tab-pane label="验收单明细" name="third">
                        <keep-alive>
                            <purchaseList
                                ref="purchaseList"
                                :detail="detailInfo"
                                :settlementList="settlementList"
                            />
                        </keep-alive>
                    </el-tab-pane>
                    
                    <el-tab-pane label="附件" name="fouth" class="file-group">
                        <fileInfo
                            ref="contractAppendix"
                            v-model="fileList"
                            state="edit"
                            v-if="isTrue"
                        ></fileInfo>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <!--  按钮  -->
        <el-bottom-guide>
            <ul class="ccui-bottom-button">
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="submitHandleKeep"
                    >暂存
                    </el-button>
                </li>
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-save"
                        @click="submitHandle(0)"
                    >保存并校验
                    </el-button>
                </li>
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-cancel"
                        @click="submitHandle(1)"
                    >保存并提交
                    </el-button>
                </li>
                <div class="ccui-bottom-guide-divider"/>
                <li>
                    <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
                    >返回
                    </el-button>
                </li>
            </ul>
        </el-bottom-guide>
    </div>
</template>

<script>
import jsList from "../js";
import baseInfo from "./baseInfo";
import financeInfo from "./financeInfo";
import purchaseList from "./purchaseList";
import fileInfo from "@/basa/components/public/uploadInfo3";

import {
    getSettlementById,
    getSmpPcConcById,
    saveSettlement,
    submitSettlement,
    tsSettlement
    // selectSettlementCount
} from "../api/settlement-approval";
import Bus from "@/app/settlement-management/settlement-maintenance-approval/components/bus";
// import BigNumber from "bignumber.js";
// import Mixin from "../mixins";
export default {
    // mixins: [Mixin],
    inject: ["reload"],
    props: {
        state: {
            type: String,
            default: "edit"
        }
    },
    components: {
        baseInfo,
        financeInfo,
        purchaseList,
        fileInfo
    },
    data() {
        return {
            settlementForm: {
                duration: [],
                contractId: null,
                pcConcId: "", // 基础合同id
                scConcId: "", // 结算申请单id
                contractName: "", // 合同名称
                contractCode: "", // 合同编号
                partyAName: "", // 合同甲方
                partyBId: "", // 合同乙方id
                partyBName: "", // 合同乙方
                supplierName: "", //供应商
                taxRatePercent: "", // 税率
                nowTotalContractPriceIncludeTax: "", // 合同金额（含税）
                settleTotalAmtIncludeTax: "", // 开累结算金额（含税）
                payedTotalAmtIncludeTax: "", // 开累支付金额
                currSetCount: 0, // 结算数量
                currSetMoney: 0, // 结算金额
                contractBalance: "", // 合同余额（含税）
                settlementNum: "", // 结算单编号
                settlementPeriod: "", // 结算期次
                currentSettlePayAmtIncludeTax: "", // 本期支付金额
                currentSettleAmtIncludeTax: "", // 本期结算金额（含税）
                currentSettleUnpayAmtIncludeTax: "", // 本期结算未支付金额（含税）
                paymentNum: "", // 支付单编号
                compiler: "", // 编制人
                compilerId: "", // 编制人id
                paymentApplyDate: "", // 支付申请日期
                remarks: "", // 备注
                reportInOrgName: "",
                reportInOrgId: null,
                reportUsername: "",
                reportTime: "",
                thirdCategoriesOfName: "",
                currencyCode: "",
                currencyName: "",
                settlementStart: "",
                settlementEnd: ""
            },
            showFileList: true,
            showFinanceInfo: false,
            fileList: [],
            files: [],
            jsList,
            breadcrumbLastItem: "结算单",
            settlementName: "",
            activeName: "first",
            isTrue: false,
            detailInfo: {},
            isFocus: "baseInfo",
            uploadList: [],
            myId: "",
            tabBtn: [
                {label: "基本信息", value: "baseInfo"},
                {label: "财务信息", value: "financeInfo"},
                {label: "采购清单", value: "purchaseList"}
            ],
            summaryArr: ["subContractorsName"],
            tableTheadOptions: [
                {
                    label: "合同编号",
                    prop: "subContractName",
                    width1: 120
                },
                {
                    label: "合同名称",
                    prop: "subContractorsName"
                }
            ],
            oneLineTableData: [
                {subContractName: 1, subContractorsName: 1},
                {subContractName: 1, subContractorsName: 1},
                {subContractName: 1, subContractorsName: 1},
                {subContractName: 1, subContractorsName: 1}
            ],
            arr1: [
                {id: 1, name: "aa"},
                {id: 2, name: "bb"},
                {id: 3, name: "cc"}
            ],
            arr2: [
                {id: 1, name: "aa"},
                {id: 2, name: "bb"}
            ],
            a: [],
            settlementList: [],
            settlementList1: [],
            breadUrl: ""
        };
    },
    created() {
        if (this.isTz == 1) {
            this.breadItem = "结算单台账";
            this.breadUrl = "/settlement-management/settlement-standing-book";
        } else {
            this.breadItem = "结算单维护";
            this.breadUrl = "/settlement-management/settlement-maintenance-approval";
        }
        this.myId = this.$route.params.id;
    },
    activated() {
        this.init();
    },
    deactivated() {
        // this.nextIsTrue();
    },
    mounted() {
        Bus.$on("borthsettlementList", () => {
            this.settlementList = []; // 当合同改变时，结算单明细清空
        });
    },
    methods: {
        clickTabs(data) {
            switch (data.name) {
                case "second" :

                    // this.$refs["financeInfo"].$refs["tableList"].doLayout(true);
                    // this.$refs["financeInfo"].handleTableLoading();
                    break;
                case "third" :
                    // this.$refs["purchaseList"].handleTableLoading();
                    break;
            }
        },
        async init() {
            this.showFileList = false;
            const data = {
                ids: [this.myId]
            };
            var res = await getSettlementById(data);
            this.settlementForm = res.data.data.settlement;
            this.settlementForm.approvalAdoptTime = this.settlementForm
                .approvalAdoptTime
                ? this.settlementForm.approvalAdoptTime.substr(0, 10)
                : "";
            this.settlementName = this.settlementForm.settlementName;
            // 51 gistUploadIds 52 otherUploadIds
            res.data.data.gistFiles.map(e => {
                e.fileType = 51;
                e.fileTypeName = "结算依据";
            });
            res.data.data.otherFiles.map(e => {
                e.fileType = 52;
                e.fileTypeName = "其他";
            });
            this.fileList = [...res.data.data.gistFiles, ...res.data.data.otherFiles];
            this.fileList.sort(this.handleSort('sn'));
            this.isTrue = true;
            this.settlementList = res.data.data.settlementList;
            this.settlementList.forEach(row => {
                if (
                    row.categoryCode &&
                    (row.categoryCode.substr(0, 4) == "1305" ||
                        row.categoryCode.substr(0, 4) == "1306" ||
                        row.categoryCode.substr(0, 4) == "1307" ||
                        row.categoryCode.substr(0, 4) == "1308" ||
                        row.categoryCode.substr(0, 4) == "1309" ||
                        row.categoryCode.substr(0, 6) == "990103")
                ) {
                    this.$set(row, "isCategories", 1);
                    this.$set(row, "settlementCount", row.residualSettlementNumber);
                }
                this.$set(row, "mergedId", row.acceptListId);
                
                if (row.acceptTime != null && row.acceptTime.length > 10) {
                    row.acceptTime = row.acceptTime.substr(0, 10);
                }
                // row.unitPriceWithTax1 = (+row.unitPriceWithTax).toFixed(2);
                row.acceptCount1 = row.acceptCount ? (+row.acceptCount).toFixed(2) : "";
                row.acceptanceCode = row.acceptCode;
                row.manufacturerBrand = row.brand;
                // row.moneyWithTax = (+row.moneyWithTax).toFixed(2);
                this.$set(row, "moneyWithTax", (+row.moneyWithTax).toFixed(2));
                row.orderCount = row.orderCount
                    ? (+row.orderCount).toFixed(3)
                    : row.orderNumber
                        ? (+row.orderNumber).toFixed(3)
                        : "";
            });
            if (this.state === "edit") {
                // this.getRegisterInfo();
            } else {
                this.detailInfo = Object.assign({}, {state: this.state});
                this.isTrue = true;
            }
            
            getSmpPcConcById({
                concId: res.data.data.settlement.contractId,
                isShowPageLoading: true
            }).then(res => {
                this.settlementForm.smpConcMatLessList =
                    res.data.data.smpConcMatLessList;
                this.settlementForm.smpPcConc = res.data.data.smpPcConc;
                if (this.$route.params.id) {
                    this.showFinanceInfo = true;
                    this.$nextTick(() => {
                        this.settlementList.forEach(item => {
                            item.acceptCount = item.acceptCount ? (+item.acceptCount).toFixed(3) : "";
                            item.unTransportCount = item.unTransportCount ? (+item.unTransportCount).toFixed(3) : "";
                            item.settlementCount = item.settlementCount ? (+item.settlementCount).toFixed(3) : "";
                            item.unitPriceWithTax = item.unitPriceWithTax ? (+item.unitPriceWithTax).toFixed(2) : "";
                            item.orderCount = item.orderCount? (+item.orderCount).toFixed(3) : item.orderNumber? (+item.orderNumber).toFixed(3) : "";
                        });
                        // console.log(this.$refs["financeInfo"].handleTable(), 'this.$refs["financeInfo"]');
                        this.$refs["financeInfo"].handleTable();
                        this.$refs["purchaseList"].showTableData = this.settlementList.filter(e => e.isMainInventory == 0 && e.isOtherCost == 0 && !e.isCategories);
                        this.$refs["financeInfo"].$refs["tableList"].doLayout();
                    });
                   
                } else {
                    this.showFinanceInfo = true;
                }
            });
        },
        
        // 保存 提交
        submitHandle(operType) {
            if (
                !this.settlementForm.settlementStart ||
                !this.settlementForm.settlementEnd ||
                this.settlementForm.settlementName == "" ||
                this.settlementForm.settlementName == undefined ||
                this.settlementForm.contractCode == "" ||
                this.settlementForm.supplierName == ""
    
            ) {
                this.activeName = "first";
                this.$message({
                    type: "error",
                    message: "请输入必填项",
                    ccuiCustom: true,
                    duration: 1500
                });
                this.$refs.baseInfo.handleSubmit();
                this.activeName = "first";
                return;
            }
    
            let settlementCountBool = this.settlementList
                .filter(e => e.isOtherCost == 0 && !e.isCategories)
                .every(item => item.settlementCount != 0 && item.settlementCount != "");
            if (!settlementCountBool) {
                this.activeName = "second";
                this.$message.warning("结算数量不能为空/0");
                this.activeName = "second";
                return;
            }
    
            let isOtherCostZero = this.settlementList
                .filter(e => e.isOtherCost != 1 && !e.isCategories)
                .every(
                    item => item.unitPriceWithTax != "" && item.unitPriceWithTax != 0
                );
            if (!isOtherCostZero) {
                this.activeName = "second";
                this.$message.warning("单价不能为空/0");
                this.activeName = "second";
                return;
            }
    
            // 运输类 || e.isCategories  去除判断
            let isOtherCostOne = this.settlementList
                .filter(e => e.isOtherCost == 1)
                .every(
                    item =>
                        item.moneyWithTax &&
                        item.moneyWithTax != "" &&
                        item.moneyWithTax != 0 &&
                        item.taxRatePercent &&
                        item.taxRatePercent != ""
                );
            if (!isOtherCostOne) {
                this.activeName = "second";
                this.$message.warning(
                    "贴息/价格追涨/价格追跌/其他/运输类,税率/含税金额不能为空/0"
                );
                this.activeName = "second";
                return;
            }
            this.settlementList = this.handleSettlementList(this.settlementList);
            
            this.handleSaveData(operType);
        },
        handleSaveData(operType) {
            this.$refs.baseInfo.handleSubmit().then(form => {
                form.materialSource = form.smpPcConc.materialSource;
                form.billSource = "20";
                
                if (operType == 0) {
                    saveSettlement({
                        settlement: form,
                        settlementList: this.settlementList,
                        gistUploadIds: this.handleFilesParams().gistUploadIds,
                        otherUploadIds: this.handleFilesParams().otherUploadIds,
                        isShowPageLoading: true
                    }).then(res => {
                        if (res.data.code == "0") {
                            this.$message({
                                type: "success",
                                message: "保存并校验成功"
                            });
                            this.handleBack();
                        }
                    });
                } else {
                    submitSettlement({
                        settlement: form,
                        settlementList: this.settlementList,
                        gistUploadIds: this.handleFilesParams().gistUploadIds,
                        otherUploadIds: this.handleFilesParams().otherUploadIds,
                        isShowPageLoading: true
                    }).then(res => {
                        if (res.data.code == "0") {
                            this.$message({
                                type: "success",
                                message: "保存并提交成功"
                            });
                            this.handleBack();
                        }
                    });
                }
            });
        },
        // 暂存
        submitHandleKeep() {
            this.settlementList = this.handleSettlementList(this.settlementList);
            
            this.$refs.baseInfo.settlementForm.billSource = "20";
            let params = {
                settlement: this.$refs.baseInfo.settlementForm,
                settlementList: this.settlementList,
                gistUploadIds: this.handleFilesParams().gistUploadIds,
                otherUploadIds: this.handleFilesParams().otherUploadIds,
                isShowPageLoading: true
            };
            tsSettlement(params).then(res => {
                this.$message({
                    type: "success",
                    message: "暂存成功"
                });
                this.handleBack();
            });
        },
    
        // 处理settlementList入参
        handleSettlementList(data) {
            if (data.length) {
                let yunshu = [], // 运输类
                    hebingqian = [], // 没有合并的数据
                    hebinghou = [], // 合并后隐藏的数据
                    hebingMerge = [], // 合并后生成的数据
                    qita = []; // 其他类数据
                data.map(e => {
                    if (e.isCategories && e.isCategories == 1) {
                        yunshu.push(e);
                    } else if (e.isMerge == 0 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebingqian.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 0 && e.isOtherCost == 0) {
                        hebinghou.push(e);
                    } else if (e.isMerge == 1 && e.isMainInventory == 1 && e.isOtherCost == 0) {
                        hebingMerge.push(e);
                    } else if (e.isOtherCost && e.isOtherCost == 1) {
                        qita.push(e);
                    }
                });
                data = [...hebingqian, ...hebingMerge, ...yunshu, ...qita, ...hebinghou];
            
                data.forEach((item, index) => {
                    item.sn = index;
                    if (item.acceptanceCode != undefined) {
                        item.acceptCode = item.acceptanceCode;
                    }
                });
            } else {
                data = [];
            }
            return data;
        },
        
        // 处理附件入参
        handleFilesParams() {
            let gistUploadIds = [],
                otherUploadIds = [];
        
            this.fileList.map((e, i) => {
                if (e.fileType == 51) {
                    gistUploadIds.push({
                        fileDesc: e.fileDesc,
                        sn: i,
                        uploadId: e.uploadId,
                        uploadTime: e.uploadTime || e.createTime
                    });
                } else {
                    otherUploadIds.push({
                        fileDesc: e.fileDesc,
                        sn: i,
                        uploadId: e.uploadId,
                        uploadTime: e.uploadTime || e.createTime
                    });
                }
            });
            return {
                gistUploadIds: gistUploadIds,
                otherUploadIds: otherUploadIds
            };
        },
        // sort 排序
        handleSort(property) {
            return function (a, b) {
                return a[property] - b[property];
            }
        },
        
        handleBack() {
            this.$router.push(
                sessionStorage.getItem("fromPath") ||
                "/settlement-management/settlement-maintenance-approval/settlement-maintenance-all"
            );
            this.reload();
        },
        delrows(row) {
        },
        numrows(row) {
            if (row.coolId == 1) {
                this.settlementList.push({
                    materialCode: "B4343434433",
                    materialName: "物资名称1",
                    materialName1: "设备物资XX",
                    specifications: "中交四航局",
                    specificationsdate: "2021-04-20",
                    specificationsnum: 35,
                    measuringUnit: 74,
                    measuringUnit2: 54,
                    measuringUnit1: 17,
                    measuringUnit3: "沟通是好的1",
                    measuringUnit4: "444DDDae",
                    materialNames: "设备",
                    specifications1: "张三",
                    measuringUnits: "鑫科集团"
                });
            } else if (row.coolId == 2) {
                this.settlementList.push({
                    materialCode: "B4343434434",
                    materialName: "物资名称2",
                    materialName1: "设备物资X1",
                    specifications: "中交四航局",
                    specificationsdate: "2021-04-20",
                    specificationsnum: 38,
                    measuringUnit: 345,
                    measuringUnit2: 65,
                    measuringUnit1: 14,
                    measuringUnit3: "沟通是好的2",
                    measuringUnit4: "444DDDae",
                    materialNames: "设备",
                    specifications1: "张三",
                    measuringUnits: "鑫科集团"
                });
            } else {
                this.settlementList.push({
                    materialCode: "B4343434435",
                    materialName: "物资名称3",
                    materialName1: "设备物资X2",
                    specifications: "中交八航局",
                    specificationsdate: "2021-04-12",
                    specificationsnum: 355,
                    measuringUnit: 764,
                    measuringUnit2: 524,
                    measuringUnit1: 117,
                    measuringUnit3: "沟通是好的3",
                    measuringUnit4: "444DDDae",
                    materialNames: "设备",
                    specifications1: "张三",
                    measuringUnits: "鑫科集团"
                });
            }
        }
    },
    destroyed() {
        Bus.$off("borthsettlementList");
    }
};
</script>
<style lang="scss" scoped>
/deep/ .file-group .el-group-title .group-content {
    margin-top: 40px;
}

/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
    top: 0;
}

/deep/ .el-tabs__customize {
    padding-bottom: 50px;
}
</style>
